package goods;

import enums.GoodsStatus;
import enums.GoodsType;
import models.constants.DeletedStatus;
import models.merchant.Merchant;

import models.weixin.WebUser;
import models.weixin.amount.RechargeCombo;
import order.OrderSource;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import play.Logger;
import play.db.jpa.JPA;
import play.db.jpa.Model;
import product.ProductSpec;
import utils.DateUtil;

import javax.persistence.*;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 商品.
 */
@Entity
@Table(name = "goods")
public class Goods extends Model {

    /**
     * 商品名称
     */
    @Column(name = "name")
    public String name;
    /**
     * 规格
     */
    @Column(name = "spec")
    public String spec;

    /**
     * 单位
     */
    @Column(name = "unit")
    public String unit;

    /**
     * 状态，包括：NEW/OPEN/CLOSE
     */
    @Enumerated(EnumType.ORDINAL)
    public GoodsStatus status;

    /**
     * Goods 类型。 目前只有一种 product
     */
    @Enumerated(EnumType.STRING)
    public GoodsType type;

    /**
     * 相关联产品 Id
     */
    @Column(name = "serial_id")
    public Long serialId;


    /**
     * 主图片路径
     */
    @Column(name = "main_image_url")
    public String img;

    /**
     * 开始时间
     */
    @Column(name = "begin_at")
    public Date beginAt;


    /**
     * 结束时间
     */
    @Column(name = "endAt")
    public Date endAt;


    /**
     * 销售单价
     */
    @Column(name = "sale_price")
    public Double salePrice;

    /**
     * 排列顺序
     */
    @Column(name = "display_order")
    public Integer displayOrder;

    /**
     * 逻辑删除,0:未删除，1:已删除
     */
    @Enumerated(EnumType.ORDINAL)
    public DeletedStatus deleted;

    /**
     * 订单创建时间
     */
    @Column(name = "created_at")
    public Date createdAt;

    /**
     * 更新时间
     */
    @Column(name = "updated_at")
    public Date updatedAt;

    /**
     * 关联商户
     */
    @JoinColumn(name = "merchant_id")
    @ManyToOne
    public Merchant merchant;



    /**
     * 更新对象.
     */
    public static Goods update(Long id, Goods newObject) {
        Goods goods = Goods.findById(id);
        if (goods == null) {
            return null;
        }
        goods.name = newObject.name;
        goods.save();
        return goods;
    }

    public static Boolean delete(Long id) {
        Goods goods = Goods.findById(id);
        if (goods == null) {
            return Boolean.FALSE;
        }
        goods.deleted = DeletedStatus.DELETED;
        goods.save();
        return Boolean.TRUE;
    }

    public static Goods findOrCreateForProduct(){
        Goods goods = new Goods();

        return goods ;
    }






    public static Goods createTypeTimeGoodsForUser(GoodsType goodsType, WebUser webUser , BigDecimal amount) {
        // 组成一个 PRODUCT_1_2017012011001200  类型_id_时间戳
        String goodsName = goodsType.toString() + "_" + webUser.id+"_"+amount;
        Goods goods = new Goods();
        goods.name = goodsName;
        goods.status = GoodsStatus.OPEN;
        goods.deleted = DeletedStatus.UN_DELETED;
        goods.salePrice = amount.doubleValue();
        goods.displayOrder = 1;
        goods.img = webUser.headImgUrl;
        goods.type = goodsType;
        goods.serialId = webUser.id;
        goods.save();
        return goods;
    }


    public static Goods createRechargeCombo(GoodsType goodsType , RechargeCombo rechargeCombo) {
        String goodsName = goodsType.toString() + "套餐";
        Goods goods = new Goods();
        goods.name = goodsName;
        goods.status = GoodsStatus.OPEN;
        goods.deleted = DeletedStatus.UN_DELETED;
        goods.salePrice = rechargeCombo.rechargeAmount;
        goods.displayOrder = 1;
        goods.img = null;
        goods.type = goodsType;
        goods.serialId = rechargeCombo.id;
        goods.save();
        return goods;
    }



    public static Goods findOrCreateProductGoods(GoodsType goodsType, String productName , Double amount, String img, Long productId) {
        // 组成一个 PRODUCT_1_2017012011001200  类型_id_时间戳
        String goodsName = goodsType.toString() + "_" + productName;
        Goods goods = Goods.find("name = ? and deleted = ?" , goodsName , DeletedStatus.UN_DELETED).first();
        if(goods == null) {
            goods = new Goods();
            goods.name = goodsName;
            goods.status = GoodsStatus.OPEN;
            goods.deleted = DeletedStatus.UN_DELETED;
            goods.salePrice = amount;
            goods.displayOrder = 1;
            goods.img = img;
            goods.type = goodsType;
            goods.serialId = productId;
            goods.save();
        }
        return goods;
    }



    /**
     *第三方订单
     * @param goodsType
     * @param orderSource
     * @param orderNo
     * @param amount
     * @return
     */
    public static Goods createThirdPartytGoods(GoodsType goodsType , OrderSource orderSource , String orderNo ,Double amount){

        Goods goods = new Goods();
        goods.name = orderNo;
        goods.status = GoodsStatus.OPEN;
        goods.salePrice = amount;
        goods.displayOrder = 1 ;
        goods.type = goodsType;
        goods.serialId = orderSource.id;
        goods.deleted = DeletedStatus.UN_DELETED;
        goods.createdAt = new Date();
        goods.save();
        return goods;
    }


    public static Goods getGoodsByProductId(Long productId){
        return Goods.find("deleted = ? and serial = ? " , DeletedStatus.UN_DELETED , "PRODUCT_"+productId).first();
    }
    /**
     * 把响应的goods 相关的产品ID 返回
     * @param goods
     * @return
     */
    public static Long separationId(Goods goods) {
        Long productId = goods.serialId;
        if(productId != null && productId > 0) {
            return productId;
        }
        return productId;
    }

    public static void updateCodeBySpec(ProductSpec spec) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("update goods g set g.code = '"+ spec.barCode +"' where g.serial_id in (select psm.id from product_spec_merchants psm where psm.product_spec_id = " +spec.id+ ")");
        Logger.info("Update SQL : %s :" , stringBuilder.toString());
        JPA.em().createNativeQuery(stringBuilder.toString()).executeUpdate();
    }

    /**
     * 根据商品Id删除商品
     * @param specMerchantIds
     */
    public static void deleteBySpecMerchant(String specMerchantIds){
        String updateSql = " update  goods a set a.deleted = 1 where a.id in  ("+specMerchantIds+")" ;
        JPA.em().createNativeQuery(updateSql).executeUpdate();
    }

    public static Goods getGoodsById(Long goodId){
        return Goods.find("deleted = ? and id = ? " , DeletedStatus.UN_DELETED , goodId).first();
    }

    public static List<Map<String,Object>> findByRoom(long roomId) {
        Date today = new Date();
        String start = DateUtil.dateToString(today, "yyyy-MM-dd") + " 00:00:00";

        String sqlSelect="select a.* from goods a, order_items b where a.id = b.goods_id and a.deleted='" + DeletedStatus.UN_DELETED + "' ";
        sqlSelect += " and a.serial_id=" + roomId;
        sqlSelect += " and a.type='" + GoodsType.SPORTS_ROOMS + "'";
        sqlSelect += " and a.begin_at is not null";
        sqlSelect += " and a.begin_at >='" + start + "'";
        sqlSelect += " order by a.begin_at desc";

        Query query=Goods.em().createNativeQuery(sqlSelect);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        return query.getResultList();
    }



}
